package com.ht.api.bigtask.impl.wxxd;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ht.api.bigtask.BaseBigTask;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信小店初始化任务：查询订单列表
 * @author asq
 * @createTime 2025年4月9日 09:18:22
 */
@Slf4j
public class QueryOrderListTask extends BaseBigTask {
	/** 接口:获取订单列表 */
	private static final long API_ID_ORDER_LIST = 1909578011380944896L;
	/** 接口:获取订单详情 */
	private static final long API_ID_ORDER_INFO = 1909595491327414272L;

	@Override
	protected void doExecute(String appId, JSONObject context, Entity bean) {
	    long time = System.currentTimeMillis();
	    
		// 拉取订单的时候，从2022年12月1日开始拉取，拉取到2022年12月31日结束，受接口限制，每次只能拉7天
		long startTimestamp = DateUtil.parse("2022-12-01").getTime() / 1000;
		long endTimestamp = DateUtil.parse("2022-12-31").getTime() / 1000;
		long day7Second = 60 * 60 * 24 * 7; // 7天时间的总秒数
		
		// 用多线程并发获取订单详情
		ExecutorService executor = Executors.newFixedThreadPool(10);
		
		// 获取订单列表
		List<String> orderIdList = new ArrayList<>();
		long nextTimestamp = Math.min(endTimestamp, startTimestamp + day7Second);
		while (nextTimestamp > startTimestamp) {
			JSONObject param = JSONUtil.createObj()
					.set("create_time_range.start_time", startTimestamp)
					.set("create_time_range.end_time", nextTimestamp);
			String str = OpenUtil.call(appId, API_ID_ORDER_LIST, param);
			JSONObject entity = JSONUtil.parseObj(str);
			JSONArray orderIds = entity.getJSONArray("order_id_list");
			for (int i = 0; i < orderIds.size(); i++) {
				orderIdList.add(orderIds.getStr(i));
			}
			
			// 拉取下一个7天的数据
			startTimestamp = nextTimestamp;
			nextTimestamp = Math.min(endTimestamp, startTimestamp + day7Second);
		}
		
		// 循环获取订单详情
		DbList list = DbList.create();
		CountDownLatch latch = new CountDownLatch(orderIdList.size());
		for (int i = 0; i < orderIdList.size(); i++) {
			String orderId = orderIdList.get(i);
			
			// 多线程并发拉取订单详情
			executor.submit(() -> {
				try {
					String strInfo = OpenUtil.call(appId, API_ID_ORDER_INFO, JSONUtil.createObj().set("order_id", orderId));
					Entity openData = createOpenDataEntity(appId, API_ID_ORDER_INFO, JSONUtil.parseObj(strInfo));
					list.add(openData);
				} catch (Exception e) {
					log.error("[QueryOrderListTask] 拉取订单详情发生异常：{}", e.getMessage(), e);
				} finally {
					latch.countDown(); 
				}
			});
		}
		
		// 所有任务完成后继续		
		try {
            latch.await(); 
            Db.insertBatchWithStream(getTenantStreamConfig(appId), list);
            log.info("[QueryOrderListTask] 全部任务完成，订单数：{}，耗时：{}ms", list.size(), (System.currentTimeMillis() - time));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
            log.error("等待并发获取订单详情任务完成时被中断", e);
        }
	}


}
